﻿using DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 串口扫码枪
{
    public partial class FrmMain : Form
    {
        private ScannerLib scannerLib = new ScannerLib();

        //private ScannerLib scannerLibTransfer = new ScannerLib();

        public FrmMain()
        {
            InitializeComponent();
        }

        private void tsb_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                scannerLib.Connect("COM4", 9600, Parity.None, 8, StopBits.One);

                // 这是向虚拟串口发送数据的示例（为了演示接收的数据发送到2个上位机上）
                //scannerLibTransfer.Connect("COM2", 9600, Parity.None, 8, StopBits.One);

            }
            catch (Exception ex)
            {
                AddLog("连接失败:" + ex.Message);
                return;
            }

            scannerLib.CodeRcvEvent += ScannerLib_CodeRcvEvent;

            AddLog("连接成功");

        }

        private void ScannerLib_CodeRcvEvent(object sender, EventArgs e)
        {
            // 发送到虚拟串口的另外一端
            //scannerLibTransfer.Send(sender.ToString());
            AddLog(sender.ToString().Replace("\n","\r\n"));
        }

        private void tsb_DisConn_Click(object sender, EventArgs e)
        {
            scannerLib.Disconnect();
            scannerLib.CodeRcvEvent -= ScannerLib_CodeRcvEvent;
            AddLog("连接断开");
        }

        private void AddLog(string info)
        {
            if (this.txtInfo.InvokeRequired)
            {
                Invoke(new Action(() =>
                {
                    this.txtInfo.AppendText(DateTime.Now.ToString("HH:mm:ss") + "  " + info + Environment.NewLine);
                }));
            }
            else
            {
                this.txtInfo.AppendText(DateTime.Now.ToString("HH:mm:ss") + "  " + info + Environment.NewLine);
            }

        }
    }
}
